import Vue from "vue";
import VueRouter from "vue-router";
import { getToken } from "@/utils/token.js";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/Login/Login.vue"),
  },
  {
    path: "/home",
    name: "home",
    redirect: "/welcome",
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/Home/Index.vue"),
    children: [
      {
        path: "/welcome",
        name: "welcome",
        component: () =>
          import(
            /* webpackChunkName: "about" */ "../views/Home/Welcome/Welcome.vue"
          ),
      },
      {
        path: "/users",
        name: "users",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/Users/Index.vue"),
      },
      {
        path: "/roles",
        name: "roles",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/Right/Roles.vue"),
      },
      {
        path: "/rights",
        name: "rights",
        component: () =>
          import(/* webpackChunkName: "about" */ "../views/Right/Rights.vue"),
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  const tokenStr = getToken();
  if (tokenStr) {
    // 如果有token，打开登录页默认跳转到主页
    if (to.path == "/login" || to.path == "/") return next("/home");
  } else if (to.path == "/login") {
    // 如果没有token，要前往主页，则放行
    next();
  } else {
    //如果没有token，无论去哪个页面都要先登录才行
    next("/login");
  }
  next();
});

export default router;
